package resp

import (
	"errors"
	"net/http"

	"gitee.com/xinshortlink/internal/dto/resp/bizerr"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
	"github.com/google/wire"
	"go.uber.org/zap"
)

type Resp struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data"`
}

type Util struct {
	logger *zap.Logger
	trans  ut.Translator
}

func NewRespUtil(logger *zap.Logger) *Util {
	var trans ut.Translator

	zhTranslator := zh.New()
	uni := ut.New(zhTranslator, zhTranslator)
	trans, _ = uni.GetTranslator("zh")
	validate := binding.Validator.Engine().(*validator.Validate)
	err := zh_translations.RegisterDefaultTranslations(validate, trans)
	if err != nil {
		return nil
	}

	return &Util{
		logger: logger,
		trans:  trans,
	}
}

func (r *Util) Resp(ctx *gin.Context, err error, data any) {
	if err != nil {
		var e *bizerr.BizErr
		if errors.As(err, &e) {
			ctx.JSON(http.StatusOK, Resp{Code: e.Code, Message: e.Message, Data: data})
		} else {
			ctx.JSON(http.StatusOK, Resp{Code: bizerr.Server, Message: "系统繁忙，请稍候再试"})
		}

		r.logger.Error("request error", zap.String("path", ctx.FullPath()), zap.Error(err))
	} else {
		ctx.JSON(http.StatusOK, Resp{Code: bizerr.SUCCESS, Message: "SUCCESS", Data: data})
	}

}

var Set = wire.NewSet(NewRespUtil)
